/*
 * Copyright (c) 2006-2021, RT-Thread Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 * 2021-12-16     louis       the first version
 */
#include "mt25q.h"
#include "minIni.h"

void MT25Q_init(void){
    __HAL_RCC_GPIOA_CLK_ENABLE();
    rt_hw_spi_device_attach("spi1", "spi10", GPIOA, GPIO_PIN_4);  // CS 脚：PA4

    /* 使用 SFUD 探测 mt25q 从设备，并将 spi10 连接的 flash 初始化为块设备，名称 Mt25Q */
    //MT25QL128ABA
    if (RT_NULL == rt_sfud_flash_probe("MT25QL128ABA", "spi10"))
    {
        rt_kprintf("MT25Q init failed.\n");
        return;
     };
    //dfs_mkfs("elm", "MT25QL128ABA");//制作文件系统，会擦除数据，无法挂载的时候可以执行这个
    if(dfs_mount("MT25QL128ABA","/","elm",0,0) == 0) // 挂载文件系统到根目录
        rt_kprintf("MT25Q mount on /.\n");
    else
        rt_kprintf("MT25Q mount failed.\n");
    rt_kprintf("MT25Q init succeed.\n");
        return;
}
//section 为节 也就是ini文件里[ ]起来的值，key为键值
int MT25Q_readKeyValue(const char* section,const char* key){
    int result = ini_getl(section,key, -1, config_path);
    rt_kprintf("Ini file %s %s = %d.\n",section,key,result);
    return result;
}
void MT25Q_writeKeyValue(const char* section,const char* key,int value){
    ini_putl(section, key, value, config_path);
    MT25Q_readKeyValue(section,key);
}

void MT25Q_writeTest(){
 char file_path[]="/sample.txt";
 char s[] = "Dovahkiin, Dovahkiin naal ok zin los vahriin.";
 char s2[]=  "Wah dein vokul mahfaeraak ahst vaal!Ahrk fin norok paal graan fod nust hon zindro zaan.Dovahkiin, fah hin kogaan mu draal!.\n";
 int fd = open(file_path,O_WRONLY | O_CREAT);
 if (fd>= 0)
 {
     write(fd, s, sizeof(s));
     rt_kprintf("Write done.\n");

     write(fd, s2, sizeof(s2));
     close(fd);
     rt_kprintf("Write done.\n");
 }
 close(fd);

 fd = open(config_path,O_WRONLY | O_CREAT);
 char s3[] = "[TEST]\na1=1\na2=2\na3=3\na4=4\na5=5\na6=6";
 if (fd>= 0)
  {
      write(fd, s3, sizeof(s3));
      close(fd);
      rt_kprintf("Write done.\n");
  }
 close(fd);
}
void MT25Q_readJump(int fd,int size){
    char buffer[size];
    read(fd, buffer, sizeof(buffer));
}
void MT25Q_readTest(){
  char file_path[]="/sample.txt";
  char buffer[20];
  int fd = open(file_path,O_RDONLY | O_CREAT);
  if (fd>= 0)
  {
      read(fd, buffer, sizeof(buffer));
      rt_kprintf("Read from file sample.txt : %s \n", buffer);

      MT25Q_readJump(fd,60);

      read(fd, buffer, sizeof(buffer));
      close(fd);
      rt_kprintf("Read from file sample.txt : %s \n", buffer);
   }
  close(fd);
}
